package cn.wang.open.sso.shiro.realm;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.wang.open.common.util.MD5Util;
import cn.wang.open.common.util.PropertiesFileUtil;
import cn.wang.open.sso.dao.model.User;
import cn.wang.open.sso.server.service.UserService;

/**
 * 用户认证和授权自定义Realm
 */
public class UserRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    UserService userService;
    
    /**
     * 授权：验证权限时调用
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();

        LOGGER.debug("user is {}", username);
        // 当前用户所有角色
        Set<String> roles = new HashSet<>();
        roles.add("user");
        
        // 当前用户所有权限
        Set<String> permissions = new HashSet<>();

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permissions);
        simpleAuthorizationInfo.setRoles(roles);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证：登录时调用
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        // client无密认证
        String ssoType = PropertiesFileUtil.getInstance("sso-client").get("sso.type");
        if ("client".equals(ssoType)) {
            return new SimpleAuthenticationInfo(username, password, getName());
        }

        // 查询用户信息
        User user = userService.selectUserByUsername(username);
        if (null == user) {
            throw new UnknownAccountException();
        }
        if (!user.getUserPwd().equals(MD5Util.md5(password))) {
            throw new IncorrectCredentialsException();
        }
        if (!user.getStatus().equals(1)) {
            throw new LockedAccountException();
        }

        return new SimpleAuthenticationInfo(username, password, getName());
    }

}
